package yxy.game.pm2.active.command.mrsc;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import yxy.apple.logger.Logger;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.active.module.ActiveModule_每日首充;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.ActiveMessage;
import yxy.game.pm2.message.PackageMessage;
import yxy.game.pm2.message.PackageMessage.Item;

import java.util.ArrayList;

@MessageType(proto = 0x0240011A, classtype = ActiveMessage.ActMrscDrawRewardRequest.class)
public class CMD_Active_每日首充_DrawReward extends Command<ActiveMessage.ActMrscDrawRewardRequest> {

	private static final Logger logger = Logger.create(CMD_Active_每日首充_DrawReward.class);
	
	@Override
	public void execute(MessageSource messageSource, ActiveMessage.ActMrscDrawRewardRequest request) throws Exception {
		String pcode = messageSource.getTag();
		int rewardid = request.getRewardid();	//奖励组id
		ActiveMessage.ActMrscDrawRewardResponse.Builder response = ActiveMessage.ActMrscDrawRewardResponse.newBuilder();
			
		ActiveModule_每日首充 am = ActiveModule_每日首充.get(pcode,false);
		if(am == null) {
			response.setStarttime(0);
			response.setEndtime(0);
			response.setTopupexp(0);
			send(messageSource, response, Result.ActNoOpen);
			return;
		}
		
		if(!am.running()) {
			response.setStarttime(0);
			response.setEndtime(0);
			response.setTopupexp(0);
			send(messageSource, response, Result.ActNoOpen);
			return;
		}
		
		Result result = am.getstateofreward(rewardid);
		
		if(result == Result.Success) {
			JSONArray getrewardstate = am.handlegetreward(rewardid);
			for(int i = 0; i < getrewardstate.size(); i++) {
				PackageMessage.Item item = (Item) getrewardstate.get(i);
				response.addRewards(item);
			}
		}
		
		response.setStarttime(am.getTimeline().getStartTime().getMillis());
		response.setEndtime(am.getTimeline().getEndTime().getMillis());
		response.setTopupexp(am.getPayexp());
		
		JSONObject json = am.getNeedtopupexp();
		for(String key : json.keySet()) {
			ActiveMessage.NeedTopUpExp.Builder ntue = ActiveMessage.NeedTopUpExp.newBuilder();
			ntue.setId(Integer.valueOf(key));
			ntue.setNeedexp(json.getIntValue(key));
			response.addNeedtopupexp(ntue);
		}
		
		ArrayList<Integer> cangetids = am.getCangetidlist();
		for(int i = 0; i < cangetids.size(); i++) {
			response.addCangetid(cangetids.get(i));
		}
		
		ArrayList<Integer> getids = am.getGetidlist();
		for(int i = 0; i < getids.size(); i++) {
			response.addGetid(getids.get(i));
		}
		send(messageSource, response, result);
		
	}
	
	private void send(MessageSource messageSource, ActiveMessage.ActMrscDrawRewardResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}

}
